<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/17
 * Time: 10:38
 */

namespace app\system\logic;

use component\system\system_auth\SystemAuth;
use component\system\system_role\SystemRole;
use component\system\system_user\SystemUser;
use component\system\system_user_auth\SystemUserAuth;

class User
{
    /**
     * @var null
     */
    private static $instance = null;

    /**
     * @var null
     */
    private static $uuid = null;

    /**
     * 不允许实力话
     * User constructor.
     */
    protected function __construct()
    {

    }

    /**
     *  不允许克隆
     */
    private function __clone()
    {

    }

    /**
     * @return User|null
     */
    private static function instance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * @param $uuid
     * @return null|integer
     */
    public static function uuid($uuid = null)
    {
        if ($uuid) {
            self::$uuid = $uuid;
            return null;
        } else {
            return self::$uuid;
        }
    }

    /**
     * 设置用户权限
     * @param array $path
     */
    public static function setAuth(array $path = [])
    {
        if (empty($path)) {
            // 获取用户权限
            $record = SystemUserAuth::instance()->getByUserId(self::$uuid);

            $auth_id = [];
            if ($record) {
                $auth_id = $record->auth_id;
                // 获取用户组权限
                if ($record->role_id) {
                    $role = SystemRole::instance()->find(['id' => $record->role_id]);
                    if ($role) {
                        $auth_id = array_merge($auth_id, $role->auth);
                    }
                }
            }

            $auth_id = array_filter($auth_id);

            if ($auth_id) {
                $path = SystemAuth::instance()->column('path', 'id', ['id' => $auth_id]);
            }
            // 获取用户组权限
        }

        $path = is_array($path) ? array_filter($path) : [];

        if ($path) {
            cache(self::instance()->getAuthName(), $path, 86400);
        }
    }

    /**
     * @return mixed
     */
    public static function getAuth()
    {
        return cache(self::instance()->getAuthName());
    }

    /**
     * 获取用户权限缓存名称
     * @return string
     */
    private function getAuthName()
    {
        return 'user_auth_data_' . self::$uuid;
    }
}